<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class StateController extends BaseController
{
    public function change(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'changeType' => 'required|in:article,chateau,product,focus',
            'changeKey' => 'required|in:weight,online,sku',
            'changeValue' => 'required',
            'changeId' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->failed($this->error = $validator->errors()->first());
        }

        $type  = strtolower($request->input('changeType'));
        $key   = $request->input('changeKey');
        $value = $request->input('changeValue');
        $id    = $request->input('changeId',0);

        if($key == "online" && !in_array($value,['yes','no'])) {
            return $this->failed('online值参数错误');
        }

        $modelArray = [
            'article' => 'App\Model\Article',
            'chateau' => 'App\Model\WineChateau',
            'product' => 'App\Model\WineProduct',
            'focus'=>'App\Model\WineFocusPicture'
        ];

        $model = new $modelArray[$type];

        if($model = $model->find($id)) {
            $model->$key = $value;
            if($model->beforeSave() && $model->save() && $model->afterSave()){
                return $this->success($model);
            }
            return $this->failed('修改失败');
        }else{
            return $this->notFond();
        }


    }
}
